import axios from 'axios'
import adapter from 'axios-miniprogram-adapter'
import config from './config'

// 创建axios实例
const service = axios.create({
    baseURL: config.baseUrl,
    timeout: 10000,
    adapter: adapter // 使用小程序适配器
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        // 从本地存储获取token
        const token = uni.getStorageSync('token');
        if (token) {
            config.headers['Authorization'] = token;
        }
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        // 检查返回的code是否为401
        if (response.data && response.data.code === 401) {
            uni.showToast({
                title: '用户状态更改，请重新登录',
                icon: 'none',
                duration: 1500
            });
            // 3秒后跳转
            setTimeout(() => {
                uni.redirectTo({
                    url: 'pages/subpackage/components/login/login'
                });
            }, 2000);
        }
        return response.data
    },
    error => {
        return Promise.reject(error)
    }
)

export default service
